package com.sam.im.heiqun.utils;

import android.os.Environment;
import android.util.Log;

import com.sam.im.heiqun.app.App;
import com.sam.im.heiqun.entities.ImageEntity;
import com.sam.im.heiqun.entities.model.FileProEtivity;
import com.google.gson.Gson;


import org.greenrobot.eventbus.EventBus;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.List;
import java.util.UUID;


public class HttpAssist {
    public static final StringBuffer RESPONSE = new StringBuffer();
    private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10 * 10000000; // 超时时间  
    private static final String CHARSET = "utf-8"; // 设置编码  
    public static final String SUCCESS = "1";
    public static final String FAILURE = "0";

    public static ImageEntity upload(List<File> uploadFiles) {
        String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; // 内容类型
        String RequestURL = App.imageUrl + "chat/uploadImage?fileExt=png";
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            // 发送POST请求必须设置如下两行
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            con.setRequestMethod("POST");
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "CHARSET-8");
            con.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + BOUNDARY);
            DataOutputStream ds =
                    new DataOutputStream(con.getOutputStream());
            for (int i = 0; i < uploadFiles.size(); i++) {

                /**
                 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
                 * filename是文件的名字，包含后缀名的 比如:abc.png
                 *
                 */
                String name ;
                String end ;
                try {
                    end = uploadFiles.get(i).getName().substring(uploadFiles.get(i).getName().lastIndexOf("."));
                }catch (Exception e){
                    e.printStackTrace();
                    end = ".jpg";
                }

                name = System.currentTimeMillis() + ToolsUtils.getMyUserId() + ToolsUtils.getRandom() + end ;

                File uploadFile = uploadFiles.get(i);
                String filename = uploadFile.getName();
                ds.writeBytes(PREFIX + BOUNDARY + LINE_END);
                ds.writeBytes("Content-Disposition: form-data; " +
                                "name=\"fileUpload\";filename=\"" +
                        name + "\"" + LINE_END);
                ds.writeBytes(LINE_END);
                FileInputStream fStream = new FileInputStream(uploadFile);
                int bufferSize = 1024;
                byte[] buffer = new byte[bufferSize];
                int length = -1;
                while ((length = fStream.read(buffer)) != -1) {
                    ds.write(buffer, 0, length);
                }
                ds.writeBytes(LINE_END);
                    /* close streams */
                fStream.close();
            }
            ds.writeBytes(PREFIX + BOUNDARY + PREFIX + LINE_END);
            ds.flush();
            // 定义BufferedReader输入流来读取URL的响应
            int responseCode = con.getResponseCode();
            InputStream is = con.getInputStream();
            if (responseCode==200){
                Log.i("info","请求成功");
            }else {
                Log.i("info","请求失败=="+responseCode);
            }
            int ch;
            StringBuffer b = new StringBuffer();
            while ((ch = is.read()) != -1) {
                b.append((char) ch);
            }
            String s = b.toString();
            Log.i("info","返回结果=="+s);
            ds.close();
            ImageEntity imageItemEntity = new Gson().fromJson(s, ImageEntity.class);
            return  imageItemEntity ;
        } catch (Exception e) {
            Log.i("info","异常==",e);
            return  null ;
        }
    }
    public static String uploadFile(File file,String msgID,boolean sendlenth) {
        String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成  
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; // 内容类型  
        String RequestURL = App.imageUrl + "chat/uploadImage?fileExt=png";
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true); // 允许输入流  
            conn.setDoOutput(true); // 允许输出流  
            conn.setUseCaches(false); // 不允许使用缓存  
            conn.setRequestMethod("POST"); // 请求方式  
            conn.setRequestProperty("Charset", CHARSET); // 设置编码  
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
                    + BOUNDARY);
            if (file != null) {
                /**
                 * 当文件不为空，把文件包装并且上传 
                 */
                OutputStream outputSteam = conn.getOutputStream();
                DataOutputStream dos = new DataOutputStream(outputSteam);
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件 
                 * filename是文件的名字，包含后缀名的 比如:abc.png
                 *
                 */
                String name ;
                String end ;
                try {
                    end = file.getName().substring(file.getName().lastIndexOf("."));
                }catch (Exception e){
                    e.printStackTrace();
                    end = ".jpg";
                }

                name = System.currentTimeMillis() + ToolsUtils.getMyUserId() + end ;
                sb.append("Content-Disposition: form-data; name=\"fileUpload\"; filename=\""
                        + name + "\"" + LINE_END);
                sb.append("Content-Type: application/octet-stream; charset="
                        + CHARSET + LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                int available = is.available();//文件大小
                byte[] bytes = new byte[1024*4];
                int len = 0;
                int commitlen = 0 ;//提交的大小
                while ((len = is.read(bytes)) != -1) {
                    if (sendlenth) {
                        commitlen = len + commitlen;
                        float i = (float) commitlen / available;
                        DecimalFormat df = new DecimalFormat("0.00");
                        String format = df.format(i * 100);
                        Log.i("info", "上传文件的速度==" + format);
                        if (!"".equals(msgID))EventBus.getDefault().post(new FileProEtivity(format, 100 * commitlen / available, msgID,1));
                    }
                        dos.write(bytes, 0, len);
                }

                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
                        .getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码 200=成功 当响应成功，获取响应的流 
                 */

                int res = conn.getResponseCode();
                Log.i("info","返回的路径response=="+res);
                if (res == 200) {
                    String oneLine;
                    StringBuffer RESPONSE = new StringBuffer();
                    BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    while ((oneLine = input.readLine()) != null) {
                        RESPONSE.append(oneLine);
                    }
                    Log.i("info","返回的路径response=="+ RESPONSE);
                    return RESPONSE.toString();
                } else {
                    return "0";//这里也返回0 以便后面做判断
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return FAILURE;
    }

    public interface fileDownFinish {
        void onFinishDown(String path);
    }

    static String pathName = "";

    public static String fileDown(String urlStr, int poi,String msgID) {
        String path = "easyfile";
        OutputStream output = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
               Log.i("info","sd卡存在可读写");
            String SDCard = Environment.getExternalStorageDirectory() + File.separator;
            //pathName = ToolsUtils.getFilepathName(urlStr);//文件存储路径
           // Log.i("info","pathname=="+pathName);
                String[] split = urlStr.split("/");
                String s = split[split.length - 1];
                pathName  = SDCard+path+File.separator+s;
                File file = new File(pathName);
            InputStream input = conn.getInputStream();
            int available = conn.getContentLength();//总大小
            int len = 0;
            int commitlen = 0 ;//提交的大小
            if (file.exists()) {//文件已存在 不重复下载
               Log.i("Info","文件已经存在，不需再次下载");
                return "0";
            } else {
                String dir = SDCard+ path;
                Log.i("info", "存贮的路径==" + dir);
                File newfile = new File(dir);
                newfile.mkdir();//新建文件夹
                file.createNewFile();//新建文件
                output = new FileOutputStream(file);
                //读取大文件
                byte[] buffer = new byte[4*1024];
                while ((len = input.read(buffer)) != -1) {
                    commitlen = len + commitlen;
                    float i = (float) commitlen / available;
                    DecimalFormat df = new DecimalFormat("0.00");
                    String format = df.format(i * 100);
                    output.write(buffer,0,len);
                    EventBus.getDefault().post(new FileProEtivity(format, 100 * commitlen / available, msgID, 0));
                }
                output.flush();
                //output.close();

            }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            return "异常";
        } finally {
            return pathName ;
           /* Message msg = new Message();
            msg.what = Constant.ADAPTER_VOICE_FROM_DOWN_FINISH;
            msg.obj = pathName;
            msg.arg1 = poi;
            mHandler.sendMessage(msg);*/
        }
    }
    /*public static void uploadfiles(List<String> files){
        try {
            HttpRequestWithBody accept = Unirest.post("http://oa.hewenjun.cn/wmsMobile/chat/uploadImage")
                    .header("accept", "application/json");


            for (int i = 0; i < files.size(); i++) {
                String s = files.get(i);
                String[] split = s.split("/");
                accept.field(split[split.length-1],s);
            }
            HttpResponse<String> stringHttpResponse = accept.asString();
            Log.i("info","文件上传成功=="+stringHttpResponse.getBody());

        } catch (UnirestException e) {
            e.printStackTrace();
        }




    }*/

}  
